import React from 'react';
import { ListView, Badge, Checkbox } from 'antd-mobile';
import { connect } from 'dva';

const cssAnimate = [' slideInDown ', ' zoomInRight ', ' zoomInUp ', ' slideInLeft ', ' bounceInLeft ',
' bounceInRight ', ' bounceInUp ', ' bounceInDown '];
const animateCount = cssAnimate.length;
let animated = false;

function getRandomNum(){
  return Math.floor(Math.random()*(animateCount));
}

function ListViewBody(props) {
  return (
    <div className="am-list-body card-listview-body">
      {props.children}
    </div>
  );
}

class CardList extends React.Component {

  selectCard = (e, fragmentId) => {
    const { onChecked } = this.props;
    onChecked(fragmentId);
    e.stopPropagation();
  }

  renderHeader(count){
    return (
      <h3 className="listview-header">图片碎片<em>{count + " "}</em>个</h3>
    );
  }

  render(){
    const { data=[], clickAble, onChecked, code } = this.props;
    let dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    if(data.length > 0 && !animated){
      window.setTimeout(() => {
        animated = true;
      }, 1000);
    }

    dataSource = dataSource.cloneWithRows(data);

    let count = 0;
    data.forEach(item => count += item.FragmentNum);

    const row = (rowData, sectionID, rowID) => {
      let cssname = "card-listview-item animated";
      if(clickAble !== 0){
        cssname = cssname + " clickable ";
      }
      if(!animated){
        cssname = cssname + cssAnimate[getRandomNum()];
      }
      return (
        <div key={rowID} className={cssname}
          // onClick={(e) => this.selectCard(e, rowData.FragmentId)}
          >
          <Checkbox checked={rowData.checked} onClick={() => onChecked(rowData.FragmentId)}>
            <div className="card">
              <Badge text={rowData.FragmentNum} size="large">
                <img src={rowData.FragmentUrl} alt="" />
              </Badge>
            </div>
          </Checkbox>
        </div>
      );
    };

    if(code){
      return (
        <div className="alipay-box">
          <h3>您的支付宝口令红包</h3>
          <em>{code}</em>
        </div>
      );
    }else{
      return (
          <ListView
          dataSource={dataSource}
          renderHeader={() => this.renderHeader(count)}
          renderRow={row}
          renderBodyComponent={() => <ListViewBody />}
          scrollRenderAheadDistance={500}
          onEndReachedThreshold={10}
          onScroll={() => animated = true}
        />
      );
    }
  }

}

export default connect(({card}) => ({
  cardList: card.cardList,
}))(CardList)
